package com.example.week02.day2.adapters;

import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.week02.R;
import com.example.week02.day2.beans.ItemBean;

import java.util.List;

//ListView适配器
public class ListViewAdapter extends RecyclerView.Adapter<ListViewAdapter.InnerHolder> {



    // 1. 定义点击监听接口
    public interface OnItemClickListener {
        void onItemClick(int position, ItemBean item);
    }

    // 2. 添加监听器成员变量
    private OnItemClickListener mOnItemClickListener;

    // 3. 提供设置监听器的方法
    public void setOnItemClickListener(OnItemClickListener listener) {
        this.mOnItemClickListener = listener;
    }


    private final List<ItemBean> mData;

    public ListViewAdapter(List<ItemBean> data) {
        this.mData = data;
    }

    public static class InnerHolder extends RecyclerView.ViewHolder {

        private TextView title;
        private ImageView icon;

        public InnerHolder(@NonNull View itemView) {
            super(itemView);

            icon = itemView.findViewById(R.id.list_view_icon);

            title = itemView.findViewById(R.id.list_view_title);
        }

        //设置数据
        public void setData(ItemBean itemBean) {
            //开始设置数据
            icon.setImageResource(itemBean.icon);
            title.setText(itemBean.title);

        }
    }


    //创建条目的view
    @NonNull
    @Override
    public ListViewAdapter.InnerHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        //传进去view就是条目的界面
        View view = View.inflate(parent.getContext(), R.layout.item_list_view, null);

        return new InnerHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ListViewAdapter.InnerHolder holder, int position) {

        // 设置数据
        holder.setData(mData.get(position));

        // 4. 绑定点击事件
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mOnItemClickListener != null) {
                    int adapterPosition = holder.getAdapterPosition();
                    if (adapterPosition != RecyclerView.NO_POSITION) {
                        mOnItemClickListener.onItemClick(
                                adapterPosition,
                                mData.get(adapterPosition)
                        );
                    }
                }
            }
        });


    }


    //返回条目个数
    @Override
    public int getItemCount() {
        return mData != null ? mData.size() : 0;
    }

}

